package org.duiduo.config.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.duiduo.util.ThreadMDCUtil;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Component;
import org.noear.solon.cloud.CloudEventHandler;
import org.noear.solon.cloud.CloudEventInterceptor;
import org.noear.solon.cloud.model.Event;
import org.slf4j.MDC;

/**
 * CloudEvent注解拦截器
 *
 * @author liangze
 * @date 2025/9/30 11:09
 */
@Slf4j
@Component
public class CloudEventAspect implements CloudEventInterceptor {

    @Override
    public boolean doIntercept(Event event, CloudEventHandler handler) {
        String topic = event.topic();
        String group = event.group();
        // 存入链路编号
        String content = event.content();
        if (StrUtil.isEmpty(content)) {
            log.info("MQ消息处理-topic:{}, group:{}", topic, group);
            return true;
        }
        JSONObject jsonObject = JSONUtil.parseObj(content);
        String traceId = jsonObject.getStr(ThreadMDCUtil.TRACE_ID_2);
        if (StrUtil.isNotEmpty(traceId)) {
            ThreadMDCUtil.setTraceId(traceId);
        }

        log.info("MQ消息处理-topic:{}, group:{}, content:{}", topic, group, ONode.stringify(content));
        return true;
    }

}
